package huiji;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Background extends BaseObj{
    public static Image image = Toolkit.getDefaultToolkit().getImage(ClassLoader
            .getSystemResource("background.png").getPath());
    public static BufferedImage  bi;
    static public List<Background> bgList = null;
    static public int speed = 1;//背景图的速度
    static private int topY = 0;//背景图最顶点y坐标，用于背景图移动到框架之下后，重新调整背景图的y坐标



    static {
        try {
            bi = ImageIO.read(ClassLoader.getSystemResource("bg3_1.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //根据窗口高度计算背景图数量,至少为2
        int i = 1;
        while (true){
            if (++i*bi.getHeight()>=(HuijiJPanel.height+bi.getHeight()))break;
        }
        bgList = new ArrayList<>(i);
        for (int j=1;j<=i;j++){
            Background bg = new Background(bi).setY(HuijiJPanel.height-(bi.getHeight()*j));
            bgList.add(bg);
            if (i==j)topY = bg.getY();
        }
    }

    static void paintBackGroud(Graphics g){
        bgList.stream().forEach((bg)->{
            bg.paint(g);
        });
    }

    static void moveBackGroud(){
        bgList.stream().forEach((bg)->{
            bg.move();
        });
    }


    public Background(){
        setSpeed(speed);
        setX(0);//默认x轴为0
    }
    public Background(BufferedImage image) {
        super(image);
        setSpeed(speed);
        setX(0);//默认x轴为0
    }

    public Background(int x ,int y) {
        this();
        //super();
        //setImage(image);
        setX(x);
        setY(y);
        //image.getWidth();

    }

//    @Override
//    public void paint(Graphics g) {
//        super.paint(g);
//    }

    @Override
    public Background setY(int y) {
        return (Background)super.setY(y);
    }

    @Override
    public void move() {
//        System.out.println(getY());
//        System.out.println(getSpeed());
        if(getY()>=HuijiJPanel.height){
            setY(topY+getSpeed());
        }else{
            setY(getY()+getSpeed());
        }

    }
}
